package com.mall.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.entity.Order;
import com.mall.entity.OrderDetail;
import com.mall.entity.R;
import com.mall.properties.WeixinpayProperties;
import com.mall.service.IOrderDetailService;
import com.mall.service.IOrderService;
import com.mall.util.*;
import io.jsonwebtoken.Claims;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.MessageDigest;
import java.util.*;

@RestController
@RequestMapping("/my/order")
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IOrderDetailService orderDetailService;

    @Autowired
    private WeixinpayProperties weixinpayProperties;

    @RequestMapping("/create")
    @Transactional
    public R create(@RequestBody Order order, @RequestHeader(value = "token") String token) {
        Claims claims = JwtUtils.validateJWT(token).getClaims();
        if ( claims != null) {
            order.setUserId(claims.getId());
        }
        order.setOrderNo("mall"+DateUtil.getCurrentDateStr());
        order.setCreateDate(new Date());

        OrderDetail[] goods = order.getGoods();
        orderService.save(order);

        for (OrderDetail orderDetail : goods) {
            orderDetail.setMId(order.getId());
            orderDetailService.save(orderDetail);
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("orderNo", order.getOrderNo());
        return R.ok(resultMap);
    }

    /**
     * 调用统一下单预支付
     */
    @RequestMapping("/preparePay")
    public R preparePay(@RequestBody String orderNo) throws Exception{
        Order order = orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNo, orderNo));

        Map<String, Object> map = new HashMap<>();
        map.put("appid",weixinpayProperties.getAppid());
        map.put("mch_id",weixinpayProperties.getMch_id());
        map.put("nonce_str",StringUtil.getRandomString(32));

        map.put("body","mall商品购买测试");
        map.put("out_trade_no",orderNo);
         map.put("total_fee",order.getTotalPrice().movePointRight(2));
//        map.put("total_fee",1);
        map.put("spbill_create_ip","127.0.0.1");
        map.put("notify_url",weixinpayProperties.getNotify_url());
        map.put("trade_type","JSAPI");
        map.put("openid",order.getUserId());
        map.put("sign",getSign(map));

        String xml = XmlUtil.genXml(map);

        HttpResponse httpResponse = HttpClientUtil.sendXMLDataByPost(weixinpayProperties.getUrl(), xml);
        String httpEntityContent = HttpClientUtil.getHttpEntityContent(httpResponse);

        Map resultMap = XmlUtil.doXMLParse(httpEntityContent);

        if(resultMap.get("return_code").equals("SUCCESS")) {
            Map<String, Object> payMap = new HashMap<>();
            payMap.put("appId", resultMap.get("appid"));
            payMap.put("timeStamp", System.currentTimeMillis()/1000);
            payMap.put("nonceStr", StringUtil.getRandomString(32));
            payMap.put("package", "prepay_id=" + resultMap.get("prepay_id"));
            payMap.put("signType", "MD5");
            payMap.put("paySign", getSign(payMap));
            payMap.put("orderNo", orderNo);
            return R.ok(payMap);
        } else {
            return R.error(500, "系统错误，请联系管理员");
        }
    }

    /**
     * 微信支付签名算法sign
     */
    private String getSign(Map<String,Object> map) {
        StringBuffer sb = new StringBuffer();
        String[] keyArr = (String[]) map.keySet().toArray(new String[map.keySet().size()]);//获取map中的key转为array
        Arrays.sort(keyArr);//对array排序
        for (int i = 0, size = keyArr.length; i < size; ++i) {
            if ("sign".equals(keyArr[i])) {
                continue;
            }
            sb.append(keyArr[i] + "=" + map.get(keyArr[i]) + "&");
        }
        sb.append("key=" + weixinpayProperties.getKey());
        String sign = string2MD5(sb.toString());
        return sign;
    }

    /***
     * MD5加码 生成32位md5码
     */
    private String string2MD5(String str){
        if (str == null || str.length() == 0) {
            return null;
        }
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };

        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf).toUpperCase();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 订单查询 type值 0全部订单 1待付款 2待收货 3退款/退货
     */
    @RequestMapping("/list")
    public R list(Integer type, Integer page, Integer pageSize) {
        System.out.println("type="+type);

        List<Order> orderList = null;
        Map<String, Object> resultMap = new HashMap<>();

        Page<Order> pageInfo = new Page<>(page, pageSize);
        if (type == 0) {
            Page<Order> orderResult = orderService.page(pageInfo, new LambdaQueryWrapper<Order>().orderByDesc(Order::getId));
            orderList = orderResult.getRecords();
            resultMap.put("total", orderResult.getTotal());
            resultMap.put("totalPage", orderResult.getPages());
        } else {
            LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Order::getStatus, type);
            queryWrapper.orderByDesc(Order::getId);
            Page<Order> orderResult = orderService.page(pageInfo, queryWrapper);
            orderList = orderResult.getRecords();
            resultMap.put("total", orderResult.getTotal());
            resultMap.put("totalPage", orderResult.getPages());
        }

        resultMap.put("orderList", orderList);
        return R.ok(resultMap);
    }
}
